<template>
  <view :style="{ width: canvasWidth, height: canvasHeight }">
    <canvas
      :id="canvasId"
      :canvas-id="canvasId"
      @touchstart="touchStart"
      @touchmove="touchMove"
      @touchend="touchEnd"
      :style="{ width: canvasWidth, height: canvasHeight }"
    />
  </view>
</template>

<script module="ecCanvas" lang="wxs">
var touch = require('./ec-canvas/ec-canvas.wxs').touch;

module.exports = {
  touchStart: touch.touchStart,
  touchMove: touch.touchMove,
  touchEnd: touch.touchEnd
};
</script>

<script>
import * as echarts from '../static/ec-canvas/echarts';

let chartInstance = null;

export default {
  name: 'EcCanvas',
  props: {
    // e.g.: { onInit: chart => {} }
    ec: {
      type: Object,
      default: () => ({})
    },
    // canvas id，默认随机生成
    canvasId: {
      type: String,
      default: () => `ec-canvas-${Math.floor(Math.random() * 10000)}`
    },
    // 宽度（支持 rpx）
    width: {
      type: String,
      default: '100%'
    },
    // 高度（支持 rpx）
    height: {
      type: String,
      default: '100%'
    }
  },

  data() {
    return {
      canvasWidth: this.width,
      canvasHeight: this.height
    };
  },

  mounted() {
    if (!this.ec) {
      console.error('Prop "ec" is required.');
      return;
    }

    this.init();
  },

  methods: {
    init() {
      const self = this;
      const query = uni.createSelectorQuery().in(this);
      query
        .select(`#${self.canvasId}`)
        .fields({ node: true, size: true })
        .exec((res) => {
          const canvas = res[0].node;
          const width = res[0].width;
          const height = res[0].height;

          const dpr = uni.getSystemInfoSync().pixelRatio;
          canvas.width = width * dpr;
          canvas.height = height * dpr;

          const ctx = canvas.getContext('2d');
          ctx.scale(dpr, dpr);

          echarts.setCanvasCreator(() => {
            return canvas;
          });

          if (typeof self.ec.onInit === 'function') {
            chartInstance = self.ec.onInit(ctx, width, height, canvas);
          } else {
            console.error('ec.onInit is not a function.');
          }
        });
    },

    // 转发触摸事件
    touchStart(e) {
      if (chartInstance && e.touches.length > 0) {
        const touch = e.touches[0];
        chartInstance.getZr().dispatchTouchEvent({
          type: 'mousedown',
          x: touch.x,
          y: touch.y
        });
        chartInstance.getZr().dispatchTouchEvent({
          type: 'mousemove',
          x: touch.x,
          y: touch.y
        });
      }
    },
    touchMove(e) {
      if (chartInstance && e.touches.length > 0) {
        const touch = e.touches[0];
        chartInstance.getZr().dispatchTouchEvent({
          type: 'mousemove',
          x: touch.x,
          y: touch.y
        });
      }
    },
    touchEnd(e) {
      if (chartInstance) {
        const touch = e.changedTouches[0];
        chartInstance.getZr().dispatchTouchEvent({
          type: 'mouseup',
          x: touch.x,
          y: touch.y
        });
      }
    }
  },

  beforeDestroy() {
    if (chartInstance) {
      chartInstance.dispose();
      chartInstance = null;
    }
  }
};
</script>